<template>
  <base-breadcrumb
    class="UpdateStudyEduc-container fixed-container"
    :title="isResolve ? '处理' : breadcrumbTitle"
  >
    <a-spin :spinning="!!loadingState.isDetail">
      <a-card :bordered="false">
        <title-name title="基础信息" />
        <custom-form
          ref="ruleForm"
          :is-validate="true"
          :edit-model="''"
          :rules="rules"
          :form="formInfo"
          :form-list="formItemList"
          @selectNode="handleSelectOrg"
        >
          <template v-slot:sectionTitle>
            <title-name title="学习信息" />
          </template>
        </custom-form>
        <title-name title="相关附件" />
        <UploadTableNew
          ref="uploadTable"
          class="mb20"
          :disabled="isDisabled"
          business-code="PARTY04"
          :mode="pageType"
          :request-fn="getFileList"
        />
        <title-name
          v-if="!isResolve"
          title="学习人员信息"
        />
        <PartyMemberTable
          v-if="!isResolve"
          ref="memberTable"
          :use-search="isDisabled"
          :mode="pageType"
          :request-fn="getMembers"
          :request-args="{ query: { learningEducationId: $route.query.id } }"
        />
      </a-card>
      <div class="page-btn-right-top">
        <a-button
          v-if="!isDisabled && !resolveInfo"
          class="ml12"
          type="primary"
          :loading="loadingState.DRAFT"
          @click="handleSubmit('DRAFT')"
        >
          保存草稿
        </a-button>
        <a-button
          v-if="!isDisabled && !resolveInfo"
          class="ml12"
          type="primary"
          :loading="loadingState.SUBMITTED"
          @click="handleSubmit('SUBMITTED')"
        >
          发送
        </a-button>
        <a-button
          class="ml12"
          type="default"
          @click="handleClose"
        >
          关闭
        </a-button>
        <a-button
          v-if="isResolve && !resolveInfo"
          class="ml12"
          type="primary"
          :loading="loadingState.isStudy"
          :disabled="countDown > 0"
          @click="handleFinish"
        >
          <span v-if="countDown > 0">{{ countDown }}s</span>
          <span>完成学习</span>
        </a-button>
      </div>
    </a-spin>
  </base-breadcrumb>
</template>

<script>
import { finishBusinessTodo } from '@/api/commons.js'
import { getDetail, getFiles, addData, editData, getMembers, finishStudy } from '@/api/partyMasses//partyManage/studyEduc.js'
import Selector from '@/components/Select/Selector.vue'
import PartyTreeSelect from '../../componments/partyTreeSelect.vue'
import Vue from 'vue'
import Moment from 'moment'
import { PARTY_TYPE_MAP } from '@/config/businessConfig.js'
import { packageConfirm } from '@/utils/baseAction.js'
import PartyMemberTable from '../../componments/PartyMemberTable.vue'

export default {
  name: 'a' + Date.now(),
  components: {
    PartyMemberTable
  },
  data() {
    return {
      getMembers,
      isHiddenOrgSelect: false,
      loadingState: {
        isDetail: false,
        DRAFT: false,
        SUBMITTED: false,
        isStudy: false
      },
      formInfo: {},
      countDown: 9999
    }
  },
  computed: {
    // 是否是业务待办查看处理信息
    resolveInfo: {
      get() {
        return this.$route.query?.resolveInfo === 'true'
      },
      set() {}
    },
    // 是否为事项处理
    isResolve() {
      return this.$route.query.messageType === 'resolve'
    },
    pageType() {
      if (this.isAudit) {
        return 'look'
      }
      return this.$route.query.pageType || 'look'
    },
    breadcrumbTitle() {
      const map = {
        add: '新增学习教育',
        edit: '编辑学习教育',
        look: '组织学习教育'
      }
      return map[this.pageType] || map['look']
    },
    isDisabled() {
      return this.pageType === 'look'
    },
    formItemList() {
      return [
        {
          label: '学习教育名称',
          keyName: 'educationName',
          type: 'BaseInput',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '发起组织',
          keyName: 'partyOrgId',
          viewName: 'youthOrgName',
          type: PartyTreeSelect,
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          hidden: this.isHiddenOrgSelect,
          attrs: {
            returnInitNode: true,
            orgStatus: 1
          }
        },
        {
          label: '发起日期',
          keyName: 'launchTime',
          type: 'a-date-picker',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          label: '创建人',
          keyName: 'creatorName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '创建时间',
          keyName: 'createTime',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '级别',
          keyName: 'levelName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '学习时长（分钟）',
          keyName: 'learningDuration',
          type: 'BaseInputNumber',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
          attrs: {
            isInt: true,
            min: 1,
            max: 30
          }
        },
        {
          slot: true,
          keyName: 'sectionTitle',
          span: 24
        },
        {
          label: '内容摘要',
          keyName: 'contentAbstract',
          type: 'BaseTextarea',
          disabled: this.isDisabled,
          span: 24,
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        }
      ]
    },
    rules() {
      const map = {}
      this.formItemList.map((item) => {
        if (item.rules) {
          map[item.keyName] = item.rules
        }
      })
      return map
    }
  },
  created() {
    this.initPage()
    this.getActivityDetailReq()
  },
  methods: {
    async handleFinish() {
      try {
        if (this.loadingState.isStudy) return
        this.loadingState.isStudy = true
        const params = {
          educationId: this.$route.query.id
        }
        await finishStudy(params)
        await finishBusinessTodo({
          id: this.$route.query.messageId
        })
        this.$message.success('成功')
        this.handleClose()
      } catch (e) {
        console.error(e)
      }
      this.loadingState.isStudy = false
    },
    initPage() {
      const userInfo = Vue.getAcloudProvider().getUserInfo()
      const curDate = Moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      this.formInfo = {
        ...this.formInfo,
        creatorName: userInfo.name,
        launchTime: curDate,
        createTime: curDate
      }
    },
    handleSelectOrg(key, data) {
      const { orgType, id } = data
      this.formInfo = {
        ...this.formInfo,
        partyOrgId: id,
        levelName: PARTY_TYPE_MAP[orgType]
      }
      this.$nextTick(() => {
        this.$refs.ruleForm.validateField('partyOrgId')
      })
    },
    async getActivityDetailReq() {
      try {
        if (!this.$route.query.id) return
        const params = {
          id: this.$route.query.id
        }
        this.loadingState.isDetail = true
        const res = await getDetail(params)
        this.formInfo = {
          ...this.formInfo,
          ...res.data,
          fileIds: res.data.fileInfoList || []
        }
        this.isHiddenOrgSelect = true
        this.$nextTick(() => {
          this.isHiddenOrgSelect = false
        })
        // 如果是事项处理，那么开始倒计时
        if (this.isResolve) {
          this.countDown = this.formInfo.learningDuration * 60
          const timeId = setInterval(() => {
            this.countDown -= 1
            if (this.countDown < 0) {
              clearInterval(timeId)
            }
          }, 1000)
          this.$once('hook:beforeDestroy', () => {
            clearInterval(timeId)
          })
        }
      } catch (e) {
        console.error(e)
      }
      this.loadingState.isDetail = false
    },
    getFileList(params) {
      if (!this.$route.query.id) {
        return Promise.resolve()
      }
      return getFiles({ ...params, query: { learningEducationId: this.$route.query.id, type: 2 } })
    },
    /**
     * 保存草稿、提交等操作
     * @param {String} actionName 'DRAFT': 保存草稿  'SUBMITTED'：提交
     */
    handleSubmit(actionName) {
      if (actionName === 'SUBMITTED') {
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
            this.$message.warning("请填写完所有必填项信息")
            return
          }
          packageConfirm({
            content: '请确认是否发送？'
          }).then((res) => {
            if (res !== 'cancel') {
              this.invokeSave(actionName)
            }
          })
        })
      } else {
        this.invokeSave(actionName)
      }
    },
    /**
     * 保存接口调用
     */
    async invokeSave(actionName) {
      if (this.loadingState[actionName]) return
      try {
        this.loadingState[actionName] = true
        const { addIds, delIds } = this.$refs.uploadTable.getChangedFileIds()
        const { addList, delList } = this.$refs.memberTable.getChangedData()
        const params = {
          ...this.formInfo,
          status: actionName === 'SUBMITTED' ? 1 : 2, // (1：已发送/2：未发送)
          addFileIds: addIds,
          removeFileIds: delIds,
          addEducationPersonnelList: addList,
          removeEducationPersonnelList: delList
        }
        const fn = this.pageType === 'add' ? addData : editData
        await fn(params)
        this.loadingState[actionName] = false
        this.$message.success(actionName === 'DRAFT' ? '保存成功' : '提交成功')
        this.$refs.uploadTable.batchDeleteFile() // 删除文件
        this.$multiTab.close()
      } catch (e) {
        console.error(e)
        this.loadingState[actionName] = false
      }
    },
    handleClose() {
      this.$close()
    }
  }
}
</script>

<style lang="less" scoped>
.file-tips {
  color: #999999;
  padding-left: 50px;
}
</style>
